package org.crc.mailserver.receiver;

import org.crc.myvhrb.model.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * CRC
 * 2021/8/18
 */
@Component
public class MailReceiver {

    public static final Logger logger = LoggerFactory.getLogger(MailReceiver.class);

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;


    @RabbitListener(queues = "anyCcCN.mail.welcome")
    public void handler(Employee employee){
        logger.info("MailReceiver:" + employee.toString());
        // 收到消息，发送邮件
        MimeMessage msg = javaMailSender.createMimeMessage();
        // 设置邮件内容
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            // 发送邮箱地址
            helper.setTo(employee.getEmail());
            // 发送人
            helper.setFrom(mailProperties.getUsername());
            // 邮件主题
            helper.setSubject("入职欢迎");
            // 发送时间
            helper.setSentDate(new Date());
            // 上下文
            Context context = new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("posName",employee.getPosition().getName());
            context.setVariable("joblevelName",employee.getJobLevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());
            // 将上下文添加到邮件模板中，参数1： 邮件模板名，参数2：上下文内容
            String mail = templateEngine.process("mail", context);
            helper.setText(mail,true);
            // 发送邮件
            javaMailSender.send(msg);
            logger.info("邮件发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("邮件发送失败：" + e.getMessage());
        }
    }

}
